<template>
  <view class="return-add-page">
    
    <!-- 表单内容 -->
    <view class="form-card">
      <!-- 单据编号 -->
      <view class="form-item">
        <text class="label required">退库单号</text>
        <text class="value readonly">{{ formData.returnCode }}</text>
      </view>
      
      <!-- 单据名称 -->
      <view class="form-item">
        <text class="label">退库单名称</text>
        <view class="value">
          <u-input v-model="formData.returnOrderName" placeholder="请输入退库单名称" border="none" style="font-size: 32rpx;" />
        </view>
      </view>
      
      <!-- 退库人 -->
      <view class="form-item">
        <text class="label">退库人</text>
        <view class="value" @click="showUserPicker = true">
          <text class="picker-text">{{ formData.returnUserName || '请选择' }}</text>
          <u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
        </view>
      </view>
      
      <!-- 退库日期 -->
      <view class="form-item">
        <text class="label required">退库日期</text>
        <view class="value" @click="datePicker.show = true">
          <text class="picker-text">{{ formData.returnDate || '请选择' }}</text>
          <u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
        </view>
      </view>
      
      <!-- 退库存放位置 -->
      <view class="form-item">
        <text class="label">退库存放位置</text>
        <view class="value" @click="showLocationPicker = true">
          <text class="picker-text">{{ formData.returnLocation || '请选择' }}</text>
          <u-icon name="arrow-right" size="30rpx" color="#999"></u-icon>
        </view>
      </view>
      
      <!-- 备注 -->
      <view class="form-item">
        <text class="label">备注</text>
        <view class="value">
          <u-input v-model="formData.remark" placeholder="请输入备注信息" border="none" />
        </view>
      </view>
    </view>
    
    <!-- 资产列表 -->
    <view class="asset-section">
      <view class="section-header">
        <text class="section-title">资产列表</text>
        <text class="asset-count">共计: {{ selectedAssets?.length || 0 }}</text>
      </view>
      <view class="asset-list" v-if="selectedAssets && selectedAssets.length > 0">
        <view class="asset-item" v-for="(item, index) in selectedAssets" :key="index">
          <view class="asset-img-container">
            <image class="asset-img" :src="item.image ? `${BASE_URL}/File/GetImage?fileId=${item.image}` : '/static/placeholder.png'" mode="aspectFill" />
          </view>
          <view class="asset-info">
            <view class="asset-name">{{ item.assetName }}</view>
            <view class="asset-detail">资产分类: {{ item.assetClassName }}</view>
            <view class="asset-detail">资产编码: {{ item.assetCode }}</view>
            <view class="asset-detail">资产规格: {{ item.specModel }}</view>
          </view>
          <view class="asset-action">
            <u-icon name="close" size="40rpx" color="#999" @click="removeAsset(index)"></u-icon>
          </view>
        </view>
      </view>
      <view class="empty-tip" v-else>
        <text>暂无资产，请点击下方"添加"按钮添加资产</text>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="footer-btn">
      <view class="btn-group">
        <view class="btn add-btn" @click="goToSelectAssets">添加</view>
        <view class="btn reset-btn" @click="resetForm">重置</view>
        <view class="btn submit-btn" @click="submitForm">{{ isEdit ? '保存' : '提交' }}</view>
      </view>
    </view>
    
    <!-- 日期选择器 -->
    <up-datetime-picker
      :show="datePicker.show"
      mode="date"
      v-model="dateTime"
      closeOnClickOverlay
      @confirm="confirmDate"
      @cancel="datePickerClose"
      @close="datePickerClose"
    ></up-datetime-picker>
    
    <!-- 退库人选择器 -->
    <u-picker
      :show="showUserPicker"
      :columns="[userList]"
      @confirm="confirmUser"
      @cancel="showUserPicker = false"
    ></u-picker>
    
    <!-- 退库位置选择器 -->
    <u-picker
      :show="showLocationPicker"
      :columns="[locationList]"
      @confirm="confirmLocation"
      @cancel="showLocationPicker = false"
    ></u-picker>
  </view>
</template>

<script setup>
import { ref, onUnmounted } from 'vue';
import { onLoad } from "@dcloudio/uni-app";
import http, { BASE_URL } from "@/api/request";
import { generateUUID } from "@/utils";
import { t } from "@/locale/index.js"

// 表单数据
const formData = ref({
  returnCode: '系统自动生成',
  returnOrderName: '',
  returnDate: '',
  returnUser: '',
  returnUserName: '',
  returnLocation: '',
  returnLocationId: '',
  remark: ''
});

// 选中的资产列表
const selectedAssets = ref([]);

// 选择器显示状态
const showUserPicker = ref(false);
const showLocationPicker = ref(false);

// 日期选择器相关
const datePicker = ref({
  show: false
});
// 初始化为当前日期
const dateTime = ref(Date.now());

// 用户列表
const userList = ref([]);

// 位置列表
const locationList = ref([]);

// 编辑模式标识
const isEdit = ref(false);

// 页面加载时获取数据
onLoad((options) => {
  // 如果有退库单号，则为编辑模式
  if (options.returnCode) {
    isEdit.value = true;
    getReturnDetail(options.returnCode);
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: t("assetReturn.edit")
    });
  }else{
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: t("assetReturn.add")
    });
  }
  
  // 获取用户列表
  getUserList();
  
  // 获取位置列表
  getLocationList();
  
  // 监听资产选择事件和选择资产页面返回的数据
  uni.$on('assetSelected', handleSelectAssets);
});

onUnmounted(() => {
  // 移除事件监听
  uni.$off('assetSelected', handleSelectAssets);
});

// 确认日期选择
const confirmDate = (e) => {
  console.log('确认日期选择', e);
  // 处理日期值，确保它是有效的
  let timestamp;
  
  // 处理不同格式的日期返回值
  if (typeof e === 'object') {
    if (e.value !== undefined) {
      timestamp = e.value; // 处理 {value: timestamp, mode: 'date'} 格式
    } else if (e.result !== undefined) {
      timestamp = e.result; // 处理 {result: timestamp} 格式
    } else {
      timestamp = Date.now(); // 默认使用当前时间
    }
  } else {
    timestamp = e; // 直接使用传入的值
  }
  
  // 使用时间戳创建日期对象
  const date = new Date(timestamp);
  
  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    console.error('无效的日期值:', e);
    uni.showToast({
      title: '日期选择错误',
      icon: 'none'
    });
    return;
  }
  
  // 只保留年月日部分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  formData.value.returnDate = `${year}-${month}-${day}`;
  
  datePicker.value.show = false;
};

// 关闭日期选择器
const datePickerClose = () => {
  datePicker.value.show = false;
};

// 获取用户列表
const getUserList = () => {
  const data = {
    code: "Sys_GetUserNameById",
    filters: [],
    allColumnFilter: true,
    tableFilters: []
  };

  http.post("/api/module/GetViewTable", data).then((res) => {
    if (res.isSuccess && res.result && res.result.viewTable) {
      userList.value = res.result.viewTable.map(item => ({
        text: item.text,
        value: item.id
      }));
    }
  }).catch(err => {
    console.error('获取用户列表失败:', err);
    uni.showToast({
      title: '获取用户列表失败',
      icon: 'none'
    });
  });
};

// 获取位置列表
const getLocationList = () => {
  const params = [
    {
      id: generateUUID(),
      service: "Module",
      method: "getViewTable",
      param: JSON.stringify({ code: "getAssetAddressList", filters: [] }),
    },
  ];

  http.post("/api/module/GetBatchResult", params).then((res) => {
    if (res.isSuccess && res.code && res.result) {
      const locationData = res.result[0].response.data.viewTable || [];
      locationList.value = locationData.map(item => ({
        text: item.asset_address_name,
        value: item.asset_address_code
      }));
    } else {
      console.error('获取位置列表失败:', res.error);
      uni.showToast({
        title: '获取位置列表失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    console.error('获取位置列表失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};

// 确认用户选择
const confirmUser = (e) => {
  const selectedUser = e.value[0];
  formData.value.returnUser = selectedUser.value;
  formData.value.returnUserName = selectedUser.text;
  showUserPicker.value = false;
};

// 确认位置选择
const confirmLocation = (e) => {
  const selectedLocation = e.value[0];
  formData.value.returnLocationId = selectedLocation.value;
  formData.value.returnLocation = selectedLocation.text;
  showLocationPicker.value = false;
};

// 跳转到选择资产页面
const goToSelectAssets = () => {
  // 跳转到资产选择页面
  uni.navigateTo({
    url: '/components/assetsAddList/index?type=return'
  });
};

// 处理选择资产页面返回的数据
const handleSelectAssets = (assets) => {
  console.log('选择的资产 (selectAssets):', assets);
  if (Array.isArray(assets) && assets.length > 0) {
    if (!selectedAssets.value) selectedAssets.value = [];
    
    // 转换资产数据格式
    const formattedAssets = assets.map(asset => ({
      id: asset.id,
      assetId: asset.id,
      assetName: asset.asset_name,
      assetClassName: asset.asset_category,
      assetCode: asset.asset_code,
      specModel: asset.spec_model,
      image: asset.image ? asset.image.trim() : '/static/placeholder.png'
    }));
    
    // 合并选中的资产，避免重复
    const existingIds = selectedAssets.value.map(item => item.id);
    const newAssets = formattedAssets.filter(asset => !existingIds.includes(asset.id));

    selectedAssets.value = [...selectedAssets.value, ...newAssets];
  }
};

// 移除资产
const removeAsset = (index) => {
  selectedAssets.value.splice(index, 1);
};

// 重置表单
const resetForm = () => {
  formData.value = {
    returnCode: '系统自动生成',
    returnOrderName: '',
    returnDate: '',
    returnUser: '',
    returnUserName: '',
    returnLocation: '',
    returnLocationId: '',
    remark: '',
    returnState: '' // 添加状态字段初始化
  };
  selectedAssets.value = [];
};

// 获取退库单详情
const getReturnDetail = (returnCode) => {
  // 显示加载中
  uni.showLoading({
    title: '加载中...'
  });
  
  // 构建请求参数
  const data = { 
    "pageCode": "assetreturn", 
    "params": { 
      "args": [ 
        { 
          "name": "interfaceCode", 
          "value": "assetreturn.getAssetReturnOrderDetail" 
        }, 
        { 
          "name": "assetReturnCode", 
          "value": returnCode 
        } 
      ] 
    }, 
    "methodName": "getAssetReturnOrderDetail" 
  };
  
  // 调用接口
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    if (res.isSuccess && res.result) {
      // 获取主单据信息和资产列表
      const masterInfo = res.result.masterInfo || {};
      const assetList = res.result.assetDetails || [];

      // 更新表单数据
      formData.value = {
        id: masterInfo.id || '',
        returnCode: masterInfo.returnCode || returnCode,
        returnOrderName: masterInfo.returnName || '',
        returnDate: masterInfo.fReturnDate?.split(' ')[0] || '',
        returnUser: masterInfo.returnUser || '',
        returnUserName: masterInfo.returnUserName || '',
        returnLocation: masterInfo.returnLocationName || '',
        returnLocationId: masterInfo.returnLocation || '',
        remark: masterInfo.remark || '',
        returnState: masterInfo.returnState || '' // 添加状态字段
      };
      
      // 更新资产列表
      selectedAssets.value = assetList.map(asset => ({
        id: asset.id,
        assetId: asset.assetId,
        assetName: asset.assetName,
        assetCode: asset.assetCode,
        assetClassName: asset.assetClassName,
        specModel: asset.specModel,
        image: asset.image
      }));
    } else {
      uni.showToast({
        title: res.error || '获取详情失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('获取退库详情失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};

// 提交表单
const submitForm = () => {
  // 表单验证
  if (!formData.value.returnDate) {
    uni.showToast({
      title: '请选择退库日期',
      icon: 'none'
    });
    return;
  }
  
  // 显示加载中
  uni.showLoading({
    title: isEdit.value ? '保存中...' : '提交中...'
  });

  // 构建DTO对象
  const assetReturnSaveDTO = {
    id: formData.value.id,
    return_code: formData.value.returnCode,
    return_name: formData.value.returnOrderName,
    return_date: formData.value.returnDate,
    return_user: formData.value.returnUser,
    return_user_name: formData.value.returnUserName,
    return_location: formData.value.returnLocationId,
    return_location_name: formData.value.returnLocation,
    remark: formData.value.remark,
    return_state: formData.value.returnState, // 添加状态字段
    // 添加资产明细列表
    assetReturnDets: selectedAssets.value.map(asset => ({
      asset_code: asset.assetCode,
      return_location: formData.value.returnLocationId
    }))
  };
  
  // 构建请求参数
  const data = { 
    "pageCode": "assetreturn", 
    "params": { 
      "args": [ 
        { 
          "name": "interfaceCode", 
          "value": "assetreturn.saveAssetReturnOrder" 
        }, 
        { 
          "name": "assetReturnSaveDTO", 
          "value": JSON.stringify(assetReturnSaveDTO)
        }
      ] 
    }, 
    "methodName": "saveAssetReturnOrder" 
  };
  
  // 调用接口
  http.post("/api/module/Invoke", data).then((res) => {
    uni.hideLoading();
    if (res.isSuccess) {
      uni.showToast({
        title: isEdit.value ? '保存成功' : '提交成功',
        icon: 'success'
      });
      
      // 触发列表页面数据刷新
      uni.$emit('returnDataChanged');
      
      // 延迟返回，确保提示信息显示完成
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      uni.showToast({
        title: res.error || '操作失败',
        icon: 'none'
      });
    }
  }).catch(err => {
    uni.hideLoading();
    console.error('提交退库单失败:', err);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  });
};
</script>

<style>
.return-add-page {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-card {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.form-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.form-item:last-child {
  border-bottom: none;
}

.label {
  width: 200rpx;
  color: #666;
}

.required::before {
  content: '*';
  color: #ff0000;
  margin-right: 4rpx;
}

.value {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.readonly {
  color: #999;
}

.picker-text {
  color: #333;
}

.asset-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.asset-count {
  font-size: 28rpx;
  color: #666;
}

.asset-list {
  margin-top: 20rpx;
}

.asset-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1px solid #eee;
}

.asset-img-container {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
}

.asset-img {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.asset-info {
  flex: 1;
}

.asset-name {
  font-size: 28rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.asset-detail {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 6rpx;
}

.asset-action {
  display: flex;
  align-items: center;
}

.empty-tip {
  text-align: center;
  padding: 40rpx 0;
  color: #999;
}

.footer-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.btn-group {
  display: flex;
  justify-content: space-around;
}

.btn {
  width: 200rpx;
  height: 80rpx;
  border-radius: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
}

.add-btn {
  background-color: #e6f7ff;
  color: #1890ff;
}

.reset-btn {
  background-color: #f5f5f5;
  color: #666;
}

.submit-btn {
  background-color: #1890ff;
  color: #fff;
}
</style>
